/**
 * 腾讯地图坐标拾取插件
 * @date 2020年1月1日
 * @auth reubenxu
 * @emil 376332768@qq.com
 * @param {Object} exports
*/
layui.define(['jquery','layer'], function(exports) {
  var $ = layui.jquery;
  var layer = layui.layer;
  var TMap = {};
  var marker10 = "";
  var marker_n = "";
  TMap.open = function(param) {
    var appkey = param.key;
    var dialogOption = param.dialog;
    dialogOption.id = 'map-choose-dialog';
    dialogOption.type = 1;
    (dialogOption.title != undefined) || (dialogOption.title = '坐标选取');
    dialogOption.content = '';
    dialogOption.area || (dialogOption.area = ['750px','550px']);
    (dialogOption.shade != undefined) || (dialogOption.shade = .1);
    dialogOption.resize = false;
    dialogOption.skin || (dialogOption.skin = 'layer-map-choose');
    var sCallBack = param.success;
    dialogOption.success = function(layero, tIndex) {
      $(layero).children(".layui-layer-content").load('module/TMap/TMap.html', function() {
        init(tIndex);
        sCallBack && sCallBack(layero, tIndex)
      });
    };
    layer.open(dialogOption);

    function init(myIndex) {
      var urlSuffix = "&key=" + appkey + "&output=jsonp&&callback=?";
      var mapDom = document.getElementById("mapDom");
      var resDom = document.getElementById("resDom");
      var nowCity = document.getElementById("nowCity");
      var searchAdr = document.getElementById("searchAdr");
      var map = new qq.maps.Map(mapDom, {
        zoom: 10
      });
      var url3;
      var query_city;
      var listener_arr = [];
      var markerArray = [];
      var isNoValue = false;
      var label = new qq.maps.Label({
        map: map,
        offset: new qq.maps.Size(15, -12),
        draggable: false,
        clickable: false
      });
      var cityservice = new qq.maps.CityService({
        complete: function(result) {
          nowCity.children[0].innerHTML = result.detail.name;
          map.setCenter(result.detail.latLng);
        }
      });
      cityservice.searchLocalCity();
      map.setOptions({draggableCursor: "crosshair"});
      $(mapDom).mouseenter(function() {
        label.setMap(map);
      });
      $(mapDom).mouseleave(function() {
        label.setMap(null);
      });
      $("#choose-city-hover").click(function() {
        $(".city-content").fadeToggle();
      });
      qq.maps.event.addListener(map, "mousemove", function(e) {
        var latlng = e.latLng;
        label.setPosition(latlng);
        label.setContent(latlng.getLat().toFixed(6) + "," + latlng.getLng().toFixed(6))
      });
      qq.maps.event.addListener(map, "click", function(e) {
        document.getElementById("poiCur").value = e.latLng.getLat().toFixed(6) + "," + e.latLng.getLng().toFixed(6);
        url3 = encodeURI("https://apis.map.qq.com/ws/geocoder/v1/?location=" + e.latLng.getLat() + "," + e.latLng.getLng() + urlSuffix);
        $.getJSON(url3, function(result) {
          if (result.result != undefined) {
            document.getElementById("addrCur").value = result.result.address;
          } else {
            document.getElementById("addrCur").value = "";
          }
        });
      });
      qq.maps.event.addListener(map, "zoom_changed", function() {
        document.getElementById("mapLevel").innerHTML = "当前缩放等级：" + map.getZoom();
      });
      qq.maps.event.addDomListener(searchAdr, 'click', function() {
        var value = $("#addrText").val();
        var latlngBounds = new qq.maps.LatLngBounds();
        for (var i = 0, l = listener_arr.length; i < l; i++) {
          qq.maps.event.removeListener(listener_arr[i]);
        }
        listener_arr.length = 0;
        query_city = nowCity.children[0].innerHTML;
        var queryUrl = encodeURI("https://apis.map.qq.com/ws/place/v1/search?keyword=" + value + "&boundary=region(" + query_city + ",0)&page_size=9&page_index=1" + urlSuffix);
        $.getJSON(queryUrl, function(result) {
          if (result.count) {
            isNoValue = false;
            resDom.innerHTML = "";
            $.each(markerArray, function(n, ele) {
              ele.setMap(null);
            });
            markerArray.length = 0;
            $.each(result.data, function(n, ele) {
              var latlng = new qq.maps.LatLng(ele.location.lat, ele.location.lng);
              latlngBounds.extend(latlng);
              var left = n * 27;
              var marker = new qq.maps.Marker({
                map: map,
                position: latlng,
                zIndex: 10
              });
              marker.index = n;
              marker.isClicked = false;
              setAnchor(marker, true);
              markerArray.push(marker);
              var listener1 = qq.maps.event.addDomListener(marker, "mouseover", function() {
                var n = this.index;
                setCurrent(markerArray, n, false);
                setCurrent(markerArray, n, true);
                label.setContent(this.position.getLat().toFixed(6) + "," + this.position.getLng().toFixed(6));
                label.setPosition(this.position);
                label.setOptions({
                  offset: new qq.maps.Size(15, -20)
                });
              });
              listener_arr.push(listener1);
              var listener2 = qq.maps.event.addDomListener(marker, "mouseout", function() {
                var n = this.index;
                setCurrent(markerArray, n, false);
                setCurrent(markerArray, n, true);
                label.setOptions({
                  offset: new qq.maps.Size(15, -12)
                })
              });
              listener_arr.push(listener2);
              var listener3 = qq.maps.event.addDomListener(marker, "click", function() {
                var n = this.index;
                setFlagClicked(markerArray, n);
                setCurrent(markerArray, n, false);
                setCurrent(markerArray, n, true);
                document.getElementById("addrCur").value = resDom.childNodes[n].childNodes[1].childNodes[1].innerHTML.substring(3);
              });
              listener_arr.push(listener3);
              map.fitBounds(latlngBounds);
              var div = document.createElement("div");
              div.className = "info_list";
              var order = document.createElement("div");
              var leftn = -54 - 17 * n;
              order.style.cssText = "width:17px;height:17px;margin-top: 3px;float:left;background:url(" + marker_n + ") " + leftn + "px 0px";
              div.appendChild(order);
              var pannel = document.createElement("div");
              pannel.style.cssText = "width:90%;float:right;";
              div.appendChild(pannel);
              var name = document.createElement("p");
              name.style.cssText = "margin:0px;color:#0000CC";
              name.innerHTML = ele.title;
              pannel.appendChild(name);
              var address = document.createElement("p");
              address.style.cssText = "margin:0px;";
              address.innerHTML = "地址：" + ele.address;
              pannel.appendChild(address);
              if (ele.tel != undefined) {
                var phone = document.createElement("p");
                phone.style.cssText = "margin:0px;";
                phone.innerHTML = "电话：" + ele.tel;
                pannel.appendChild(phone);
              }
              var position = document.createElement("p");
              position.style.cssText = "margin:0px;";
              position.innerHTML = "坐标：" + ele.location.lat.toFixed(6) + "，" + ele.location.lng.toFixed(6);
              pannel.appendChild(position);
              resDom.appendChild(div);
              div.style.height = pannel.offsetHeight + "px";
              div.isClicked = false;
              div.index = n;
              marker.div = div;
              div.marker = marker;
            });
            $("#resDom").delegate(".info_list", "mouseover", function(e) {
              var n = this.index;
              setCurrent(markerArray, n, false);
              setCurrent(markerArray, n, true);
            });
            $("#resDom").delegate(".info_list", "mouseout", function() {
              $.each(markerArray, function(n, ele) {
                if (!ele.isClicked) {
                  setAnchor(ele, true);
                  ele.div.style.background = "#fff";
                }
              });
            });
            $("#resDom").delegate(".info_list", "click", function(e) {
              var n = this.index;
              setFlagClicked(markerArray, n);
              setCurrent(markerArray, n, false);
              setCurrent(markerArray, n, true);
              map.setCenter(markerArray[n].position);
              document.getElementById("addrCur").value = this.childNodes[1].childNodes[1].innerHTML.substring(3);
            });
          } else {
            resDom.innerHTML = "";
            $.each(markerArray, function(n, ele) {
              ele.setMap(null);
            });
            markerArray.length = 0;
            var novalue = document.createElement('div');
            novalue.id = "no_value";
            novalue.innerHTML = "对不起，没有搜索到您要找的结果!";
            resDom.appendChild(novalue);
            isNoValue = true;
          }
        });
      });
      var setAnchor = function(marker, flag) {
        var left = marker.index * 27;
        if (flag == true) {
          var anchor = new qq.maps.Point(10, 30),
            origin = new qq.maps.Point(left, 0),
            size = new qq.maps.Size(27, 33),
            icon = new qq.maps.MarkerImage(marker10, size, origin, anchor);
          marker.setIcon(icon);
        } else {
          var anchor = new qq.maps.Point(10, 30),
            origin = new qq.maps.Point(left, 35),
            size = new qq.maps.Size(27, 33),
            icon = new qq.maps.MarkerImage(marker10, size, origin, anchor);
          marker.setIcon(icon);
        }
      }
      var setCurrent = function(arr, index, isMarker) {
        if (isMarker) {
          $.each(markerArray, function(n, ele) {
            if (n == index) {
              setAnchor(ele, false);
              ele.setZIndex(10);
            } else {
              if (!ele.isClicked) {
                setAnchor(ele, true);
                ele.setZIndex(9);
              }
            }
          });
        } else {
          $.each(markerArray, function(n, ele) {
            if (n == index) {
              ele.div.style.background = "#DBE4F2";
            } else {
              if (!ele.div.isClicked) {
                ele.div.style.background = "#fff";
              }
            }
          });
        }
      }
      var setFlagClicked = function(arr, index) {
        $.each(markerArray, function(n, ele) {
          if (n == index) {
            ele.isClicked = true;
            ele.div.isClicked = true;
            var str = '<div style="width:250px;">' + ele.div.children[1].innerHTML.toString() + '</div>';
            var latLng = ele.getPosition();
            document.getElementById("poiCur").value = latLng.getLat().toFixed(6) + "," + latLng.getLng().toFixed(6);
          } else {
            ele.isClicked = false;
            ele.div.isClicked = false;
          }
        });
      }
      var city = document.getElementById("city");
      nowCity.onclick = function(e) {
        var e = e || window.event,
          target = e.target || e.srcElement;
        if (target.innerHTML == "更换城市") {
          city.style.display = "block";
          if (isNoValue) {
            bside.innerHTML = "";
            $.each(markerArray, function(n, ele) {
              ele.setMap(null);
            });
            markerArray.length = 0;
          }
        }
      };
      var url2;
      city.onclick = function(e) {
        var e = e || window.event,
          target = e.target || e.srcElement;
        if (target.className == "city_name") {
          $(".city-content").fadeOut();
          nowCity.children[0].innerHTML = target.innerHTML;
          url2 = encodeURI("https://apis.map.qq.com/ws/geocoder/v1/?region=" + nowCity.children[0].innerHTML + "&address=" + nowCity.children[0].innerHTML + urlSuffix);
          $.getJSON(url2, function(result) {
            map.setCenter(new qq.maps.LatLng(result.result.location.lat, result.result.location.lng));
            map.setZoom(10);
          });
        }
      };
      var url4;
      $("#addrText").bind('input propertychange', function() {
        $("#autoRes").fadeIn("normal", function() {
          var keyword = $("#addrText").val();
          if(keyword == null || keyword == ''){
            return;
          }
          url4 = encodeURI("https://apis.map.qq.com/ws/place/v1/suggestion/?keyword=" + keyword + "&region=" + nowCity.children[0].innerHTML + urlSuffix);
          $.getJSON(url4, function(result) {
            var ars = "";
            $.each(result.data, function(n, ele) {
              ars += '<li class="auto-res">' + ele.title + '</li>';
            });
            $("#autoRes").empty().append(ars);
            $(".auto-res").click(function() {
              $("#addrText").val($(this).text());
            });
          });
        });
        $(this).on('blur', function() {
          $("#autoRes").fadeOut();
        });
      });
    }
  };
  exports("TMap", TMap);
});